package com.etrans.web.gps.business.enterpriseTask.service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.enterpriseTask.domian.EnterpriseSwap;
import com.etrans.web.gps.business.enterpriseTask.domian.EnterpriseVo;
import com.etrans.web.gps.business.system.service.SystemService;
import com.etrans.web.gps.common.AbnomalVeVO;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.common.SendMessageRecord;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.message.MailInfo;
import com.etrans.web.gps.util.message.MailSendUtil;
import com.etrans.web.gps.util.message.SMSUtil;
import com.mongodb.BasicDBObject;

@Service
public class SendEntMessageService extends BaseService{
	
	@Autowired
	private Config config;
	
	@Autowired
	private SystemService system;
	
	public List<EnterpriseVo> queryAllEnterprise(Map<String, Object> param) {
		return selectList("enterpriseMapper.queryAllEnterprise", param);
	}
	
	public List<EnterpriseSwap> queryEnterpriseSwapByWeek(String startTime){
			try {
				HashMap<String,Object> whereMap = new HashMap<String,Object>();

				whereMap.put("analyse_date", DateUtil.getStrToDateFormat(startTime+" 00:00:00","yyyy-MM-dd hh:mm:ss"));
				List<EnterpriseSwap> listAnalyzes = MGTemplete.find("egov", "enterprise_swap_week",whereMap,EnterpriseSwap.class,true);
				Collections.sort(listAnalyzes,Collections.reverseOrder(new Comparetores()));
				int i=1;
				for (EnterpriseSwap Analyzes : listAnalyzes) {
						Analyzes.setRanking(i);
						i++;
				}
				return  listAnalyzes;
			} catch (ParseException e) {
				e.printStackTrace();
				return  null;
			}
	}
	/**
	 * 
	 * 
	 * @author RenweiWu
	 * @date 2017年9月5日
	 * @ClassName:  Comparetores  
	 * @param: Comparator<T>
	 */
	public static class Comparetores implements Comparator<EnterpriseSwap>{
		public int compare(EnterpriseSwap analyzes1, EnterpriseSwap analyzes2) {
	        int maxs=(int) (analyzes1.getScore()-analyzes2.getScore());
	         if(maxs==0){
	        	 int a1=(analyzes1.getTrack_normal()+analyzes1.getException_track_count())<=0?1:(analyzes1.getTrack_normal()+analyzes1.getException_track_count());
	        	 int a2=(analyzes2.getTrack_normal()+analyzes2.getException_track_count())<=0?1:(analyzes2.getTrack_normal()+analyzes2.getException_track_count());
	        	 int maxn = (int)(((double)analyzes1.getException_track_count()/a1)-((double)analyzes2.getException_track_count()/a2));
	        	 if (maxn==0) {
					return analyzes1.getScore()<=analyzes2.getScore()?-1:1;
				} else {
					return maxn;
				}
	         }else{
	 	        return maxs;
	         }
		}		
	}
	public List<EnterpriseSwap> queryEnterpriseSwapByMonth(String previousMonth) {
		HashMap<String,Object> whereMap = new HashMap<String,Object>();
	//	Pattern pattern = Pattern.compile("^"+previousMonth);
		whereMap.put("analyse_date", previousMonth+"-01 00:00:00");
		List<EnterpriseSwap> listAnalyzes = MGTemplete.find("egov", "enterprise_swap_month",whereMap,EnterpriseSwap.class,true);
		Collections.sort(listAnalyzes,Collections.reverseOrder(new Comparetores()));
	/*	int i=1;
		for (EnterpriseSwap Analyzes : listAnalyzes) {
				Analyzes.setRanking(i);
				i++;
		}*/
		for(int i=0 ;i<listAnalyzes.size();i++){
			EnterpriseSwap obj1 = listAnalyzes.get(i);
			EnterpriseSwap obj2 = listAnalyzes.get(i+1);
			if(obj1.getScore() == obj2.getScore()){
				if(obj1.getRanking() !=0 ){
					obj2.setRanking(obj1.getRanking());
				}else{
					obj1.setRanking(obj1.getRanking()+1);
					obj2.setRanking(obj1.getRanking()+1);
				}
			}else{
				obj1.setRanking(obj1.getRanking()+1);
				obj2.setRanking(obj1.getRanking()+1);
			}
		}
		return  listAnalyzes;
	}

	public void saveMessage(SendMessageRecord smr) {
		MGTemplete.insertOne("egov", "tips_record", smr);
	}

	public List<AbnomalVeVO> queryAbTableByEntAndMonth(String enterpriseName, String monthTime) {
		try {
			HashMap<String,Object> whereMap = new HashMap<String, Object>();
			String inputTime = monthTime.substring(2,4)+monthTime.substring(5,7);
			Pattern pattern = Pattern.compile("^"+inputTime);
			whereMap.put("_id", pattern);
			whereMap.put("enterprise_name", enterpriseName);
			//异常判断条件
			whereMap.put("is_exception_vehicle", true);
			List<AbnomalVeVO> list = MGTemplete.find("egov", "vehicle_has_problem",whereMap,AbnomalVeVO.class,true);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<AbnomalVeVO> queryAbTableByEntByTime(String enterpriseName, String startTime, String endTime) {
		try {
			HashMap<String,Object> whereMap = new HashMap<String, Object>();
			HashMap<String,Object> paramMap = new HashMap<String, Object>();
			paramMap.put("$gte", startTime);
			paramMap.put("$lte", endTime);
			whereMap.put("analyse_date", paramMap);
			whereMap.put("enterprise_name", enterpriseName);
			//异常判断条件
			whereMap.put("is_exception_vehicle", true);
			List<AbnomalVeVO> list = MGTemplete.find("egov", "vehicle_has_problem",whereMap,AbnomalVeVO.class,true);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<String> queryEnterprise(String name) {
		int areaID = this.selectOne("enterpriseMapper.queryEnterprise", name);
		HashMap<String, Object> param = new HashMap<>();
		param.put("FullID", String.format("%08d", areaID));
		return this.selectList("enterpriseMapper.queryEnterpriseList", param);
		
	}
	
	/**
	 * 发送邮件
	 * @param flag 
	 * @return 
	 * 	
	 * */
	public List<Map<String, Object>> sendMail(List<EnterpriseVo> entList, List<EnterpriseSwap> entSwapList, String msgTime, String time, boolean flag) {
		DecimalFormat dft = new DecimalFormat("0.00");
		List<Map<String, Object>> result = new ArrayList<>();
		try {
			for(EnterpriseSwap obj : entSwapList ){
				for(EnterpriseVo enterprise : entList){
					if(obj.getEnterprise_name().equals(enterprise.getName())){
						Integer enable_mail = enterprise.getEnable_email();
						if (enable_mail != null && enable_mail == 1) {
							if(enterprise.getEmail() !=null && !"".equals(enterprise.getEmail())){
								String startStr = DateUtil.getDateTimeString(DateUtil.getPreviousWeekDate(),"yyyy-MM-dd");
								String endStr = DateUtil.getDateToString(DateUtil.getPreviousWeekSunDateDate(),"yyyy-MM-dd");
								String startTime = startStr+" 00:00:00";
								String endTime = endStr+" 23:59:59";
								//获取联系人和手机号
								String contacts = enterprise.getContact();
								String email = enterprise.getEmail();
								String phone = enterprise.getPhone();
								List<AbnomalVeVO> abnomalList =null;
								Map<String,Object> model = new HashMap<String,Object>();
								//按周和按月查询问题车辆
								if("week".equals(time)){
									List<AbnomalVeVO> temp =queryAbTableByEntByTime(enterprise.getName(), startTime, endTime);
									if(!temp.isEmpty() && temp.size() != 0){
										abnomalList.addAll(temp);
									}
									 model.put("time", "第"+String.valueOf(DateUtil.getDayOfWeek(new Date())-1)+"周("+startStr+"~"+endStr+")");
								}else{
									String monthTime =DateUtil.getDateToString(DateUtil.getPreviousMonthDate(1),"yy-MM")+"-01 00:00:00";
									List<AbnomalVeVO> temp =queryAbTableByEntAndMonth(enterprise.getName(),monthTime);
									if(!temp.isEmpty() && temp.size() != 0){
										abnomalList.addAll(temp);
									}
									 model.put("time",DateUtil.getDateToString(DateUtil.getPreviousMonthDate(1),"yy-MM")+"月");
								}
							
								List<EnterpriseSwap> subList = new ArrayList<>();
								for(int i=0;i<10;i++ ){
									subList.add(entSwapList.get(i));
								}
								if(!subList.contains(obj)){
									subList.add(obj);
								}
								MailInfo info = new MailInfo();
							    info.setToAddress(email);
							    info.setSubject(config.plat_name+"业户月考核统计");
							        
							    //发送html格式
							    info.setFileName("enterpriseTemplate.html");
							    BasicDBObject dbObject = new BasicDBObject("$gte",DateUtil.getStrToDateFormat(startTime, "yyyy-MM-dd hh:mm:ss") );
								dbObject.put("$lte",DateUtil.getStrToDateFormat(endTime, "yyyy-MM-dd hh:mm:ss") );
								BasicDBObject alarmResult = new BasicDBObject("alarm_time",dbObject);								
								alarmResult.put("enterprise_id", enterprise.getId());								    
							    long alarmCount = MGTemplete.findCount("egov", "alarm_result", alarmResult);
							    alarmResult.put("history", new BasicDBObject("$ne",null));
							    long alarmDealCount = MGTemplete.findCount("egov", "alarm_result", alarmResult);
						        model.put("rank",obj.getRanking());
						        model.put("vehicleCount",obj.getVehicle_count());
						        model.put("vehicleNetCount",obj.getVehicle_access_count());
						        model.put("enterpriseName",enterprise.getName());
						        if(alarmCount !=0 ){
						        	model.put("dealRate",dft.format(alarmDealCount/alarmCount >100 ? "100" :alarmDealCount/alarmCount)+"%");
						        }else{
						        	model.put("dealRate","0.00%");
						        }
						        model.put("pic", config.image_path);
						        String entStr ="";
						        for(int i=0;i<subList.size();i++){
						        	int sum =subList.get(i).getLocation_exception_count()
						        			+subList.get(i).getSpeed_160_count()
						        			+subList.get(i).getGpstime_exception_count()
						        			+subList.get(i).getHead_exception_count();
						        	int avg = sum<=0?0:subList.get(i).getLocation_exception_count()/sum;
						        	double handleStr =subList.get(i).getVehicle_online_count()<=0?0:(avg*subList.get(i).getException_vehicle_count())/subList.get(i).getVehicle_online_count();
					            	
						        	entStr += "<tr>"
												+"<td>"+subList.get(i).getRanking()+"</td>"
												+"<td>"+dft.format(subList.get(i).getScore())+"</td>"
												+"<td>"+subList.get(i).getEnterprise_name()+"</td>"
												+"<td>"+dft.format((subList.get(i).getVehicle_access_count()/subList.get(i).getVehicle_count())*100)+"</td>"
												+"<td>"+dft.format((subList.get(i).getVehicle_online_count()/subList.get(i).getVehicle_access_count())*100)+"</td>"
												+"<td>"+dft.format(subList.get(i).getTrack_complete_rate())+"</td>"
												+"<td>"+dft.format(((subList.get(i).getTrack_normal()/(subList.get(i).getException_track_count()+subList.get(i).getTrack_normal()))*100))+"</td>"
												+"<td>"+dft.format(handleStr *100)+"</td>"
												+"<td>"+dft.format(subList.get(i).getAvg_vehicle_speed_counts())+"</td>"
												+"<td>"+dft.format(subList.get(i).getAvg_vehicle_tired_duration())+"</td>"
												+"<td>"+dft.format(subList.get(i).getReply_correct_count()/subList.get(i).getCheck_count())+"</td>"
											+"</tr>";
						        }
						        String abnomalStr="";
						        if(abnomalList != null && abnomalList.size() != 0){
							        for(AbnomalVeVO vo : abnomalList){
							        	abnomalStr +="<tr>"
														+"<td>"+vo.getVehicle_no()+"</td>"
														+"<td>"+vo.getVehicle_color_name()+"</td>"
														+"<td>"+vo.getEnterprise_name()+"</td>"
														+"<td>"+vo.getNotrack_day_count()+"</td>"
														+"<td>"+dft.format(vo.getTrack_complete_rate())+"</td>"
														+"<td>"+dft.format(((vo.getTrack_normal()/(vo.getException_track_count()+vo.getTrack_normal()))*100))+"</td>"
														+"<td>"+vo.getLocation_exception_count()+"</td>"
														+"<td>"+vo.getOverspeed_100_count()+"</td>"
														+"<td>"+vo.getOverspeed_order()+"</td>"
														+"<td>"+vo.getTired_duration()+"</td>"
													+"</tr>";
							        }
						        }
						        model.put("abnomalList",abnomalStr);
						        model.put("EntList",entStr);
						        result.add(model);
						       //是否发送短信
						       if(flag){
						        //  true 发送成功 false 失败
								boolean status = MailSendUtil.sendHtmlMail(info, model);
								if(status){
									  
									SendMessageRecord smr = new SendMessageRecord();
									smr.set_id(new ObjectId());
									smr.setEmail(email);
									smr.setPhone(phone);
									smr.setTips_time(new Date());
									smr.setTips_type(1);
									smr.setTarget_type(1);
									smr.setTarget_name(contacts);
									if("week".equals(time)){
										smr.setContent("/mail/enterprise/sendMailByWeek.html?startStr="+startStr+"&endStr="+endStr+"&id="+enterprise.getId());
									}else{
										smr.setContent("/mail/enterprise/sendMailByMonth.html?previousMonth="+DateUtil.getDateToString(DateUtil.getPreviousMonthDate(1))+"&id="+enterprise.getId());
									}
									saveMessage(smr);
								}
						       }
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 发送短信
	 * 	
	 * */
	public void sendSMS(List<EnterpriseVo> entList, List<EnterpriseSwap> entSwapList, String msgTime) {
		for(EnterpriseSwap obj : entSwapList ){
			for(EnterpriseVo enterprise : entList){
				if(obj.getEnterprise_name().equals(enterprise.getName())){
					Integer enable_sms = enterprise.getEnable_sms();
					if (enable_sms != null && enable_sms == 1) {
						if(enterprise.getPhone() !=null && !"".equals(enterprise.getPhone())){
							//获取联系人和手机号
							String contacts = enterprise.getContact();
							String phone = enterprise.getPhone() ;
							String email = enterprise.getEmail();
							String sendMessage = getSendFormat(contacts,msgTime,obj);
							String status = SMSUtil.mt(phone, sendMessage, "", "", "");
							if(status != null && !"100".equals(status)){
								SendMessageRecord smr = new SendMessageRecord();
								smr.set_id(new ObjectId());
								smr.setEmail(email);
								smr.setPhone(phone);
								smr.setTips_time(new Date());
								smr.setTips_type(0);
								smr.setTarget_type(1);
								smr.setTarget_name(contacts);
								smr.setContent(sendMessage);
								saveMessage(smr);
							}
						}
					}
				}
			}
		}
	}
	
	/*public Map<String,Object> sendMailByHref(List<EnterpriseVo> entList, List<EnterpriseSwap> entSwapList, String msgTime, String time) {
		DecimalFormat dft = new DecimalFormat("0.00");
		Map<String,Object> model = new HashMap<String,Object>();
		try {
			for(EnterpriseSwap obj : entSwapList ){
				for(EnterpriseVo enterprise : entList){
					if(obj.getEnterprise_name().equals(enterprise.getName())){
						Integer enable_mail = enterprise.getEnable_email();
						if (enable_mail != null && enable_mail == 1) {
							if(enterprise.getEmail() !=null && !"".equals(enterprise.getEmail())){
								//获取联系人和手机号
								String contacts = enterprise.getContact();
								String email = enterprise.getEmail();
								String phone = enterprise.getPhone();
								List<AbnomalVeVO> abnomalList =null;
								String startStr = DateUtil.getDateTimeString(DateUtil.getPreviousWeekDate(),"yyyy-MM-dd");
								String endStr = DateUtil.getDateToString(DateUtil.getPreviousWeekSunDateDate(),"yyyy-MM-dd");
								String startTime = startStr+" 00:00:00";
								String endTime = endStr+" 23:59:59";
								//按周和按月查询问题车辆
								if("week".equals(time)){
									
									List<AbnomalVeVO> temp =queryAbTableByEntByTime(enterprise.getName(), startTime, endTime);
									if(!temp.isEmpty() && temp.size() != 0){
										abnomalList.addAll(temp);
									}
									 model.put("time", "第"+String.valueOf(DateUtil.getDayOfWeek(new Date())-1)+"周("+startStr+"~"+endStr+")");
								}else{
									String monthTime =DateUtil.getDateToString(DateUtil.getPreviousMonthDate(1),"yy-MM")+"-01 00:00:00";
									List<AbnomalVeVO> temp =queryAbTableByEntAndMonth(enterprise.getName(),monthTime);
									if(!temp.isEmpty() && temp.size() != 0){
										abnomalList.addAll(temp);
									}
									 model.put("time",DateUtil.getDateToString(DateUtil.getPreviousMonthDate(1),"yy-MM")+"月");
								}
							
								List<EnterpriseSwap> subList = new ArrayList<>();
								for(int i=0;i<10;i++ ){
									subList.add(entSwapList.get(i));
								}
								if(!subList.contains(obj)){
									subList.add(obj);
								}
								BasicDBObject dbObject = new BasicDBObject("$gte",DateUtil.getStrToDateFormat(startTime, "yyyy-MM-dd hh:mm:ss") );
								dbObject.put("$lte",DateUtil.getStrToDateFormat(endTime, "yyyy-MM-dd hh:mm:ss") );
								BasicDBObject alarmResult = new BasicDBObject("alarm_time",dbObject);								
								alarmResult.put("enterprise_id", enterprise.getId());								    
							    long alarmCount = MGTemplete.findCount("egov", "alarm_result", alarmResult);
							    alarmResult.put("history", new BasicDBObject("$ne",null));
							    long alarmDealCount = MGTemplete.findCount("egov", "alarm_result", alarmResult);
						        model.put("rank",obj.getRanking());
						        model.put("vehicleCount",obj.getVehicle_count());
						        model.put("vehicleNetCount",obj.getVehicle_access_count());
						        model.put("enterpriseName",enterprise.getName());
						        if(alarmCount !=0 ){
						        	model.put("dealRate",dft.format(alarmDealCount/alarmCount >100 ? "100" :alarmDealCount/alarmCount)+"%");
						        }else{
						        	model.put("dealRate","0.00%");
						        }
						        model.put("pic", config.image_path);
						        String entStr ="";
						        for(int i=0;i<subList.size();i++){
						        	int sum =subList.get(i).getLocation_exception_count()
						        			+subList.get(i).getSpeed_160_count()
						        			+subList.get(i).getGpstime_exception_count()
						        			+subList.get(i).getHead_exception_count();
						        	int avg = sum<=0?0:subList.get(i).getLocation_exception_count()/sum;
						        	double handleStr =subList.get(i).getVehicle_online_count()<=0?0:(avg*subList.get(i).getException_vehicle_count())/subList.get(i).getVehicle_online_count();
					            	
						        	entStr += "<tr>"
												+"<td>"+subList.get(i).getRanking()+"</td>"
												+"<td>"+dft.format(subList.get(i).getScore())+"</td>"
												+"<td>"+subList.get(i).getEnterprise_name()+"</td>"
												+"<td>"+dft.format((subList.get(i).getVehicle_access_count()/subList.get(i).getVehicle_count())*100)+"</td>"
												+"<td>"+dft.format((subList.get(i).getVehicle_online_count()/subList.get(i).getVehicle_access_count())*100)+"</td>"
												+"<td>"+dft.format(subList.get(i).getTrack_complete_rate())+"</td>"
												+"<td>"+dft.format(((subList.get(i).getTrack_normal()/(subList.get(i).getException_track_count()+subList.get(i).getTrack_normal()))*100))+"</td>"
												+"<td>"+dft.format(handleStr *100)+"</td>"
												+"<td>"+dft.format(subList.get(i).getAvg_vehicle_speed_counts())+"</td>"
												+"<td>"+dft.format(subList.get(i).getAvg_vehicle_tired_duration())+"</td>"
												+"<td>"+dft.format(subList.get(i).getReply_correct_count()/subList.get(i).getCheck_count())+"</td>"
											+"</tr>";
						        }
						        String abnomalStr="";
						        if(abnomalList != null && abnomalList.size() != 0){
							        for(AbnomalVeVO vo : abnomalList){
							        	abnomalStr +="<tr>"
														+"<td>"+vo.getVehicle_no()+"</td>"
														+"<td>"+vo.getVehicle_color_name()+"</td>"
														+"<td>"+vo.getEnterprise_name()+"</td>"
														+"<td>"+vo.getNotrack_day_count()+"</td>"
														+"<td>"+dft.format(vo.getTrack_complete_rate())+"</td>"
														+"<td>"+dft.format(((vo.getTrack_normal()/(vo.getException_track_count()+vo.getTrack_normal()))*100))+"</td>"
														+"<td>"+vo.getLocation_exception_count()+"</td>"
														+"<td>"+vo.getOverspeed_100_count()+"</td>"
														+"<td>"+vo.getOverspeed_order()+"</td>"
														+"<td>"+vo.getTired_duration()+"</td>"
													+"</tr>";
							        }
						        }
						        model.put("abnomalList",abnomalStr);
						        model.put("EntList",entStr);
						   
							}
						}
					}
				}
			}
			return model;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	*/
	public String getSendFormat(String contacts, String msgTime, EnterpriseSwap obj) {
		DecimalFormat dft = new DecimalFormat("0.00");
		StringBuffer stb = new StringBuffer();
		stb.append("尊敬的"+contacts+"先生：以下信息为"+system.getAreaName()+msgTime+":");
		stb.append("业户："+obj.getEnterprise_name()+",\t");
		stb.append("排名："+obj.getRanking()+",\t");
		stb.append("得分："+obj.getScore()+",\t");
		
		int vehicle_count = obj.getVehicle_count();
		stb.append("车辆入网率："+(vehicle_count <= 0 ? 0 : dft.format(obj.getVehicle_access_count()/vehicle_count))+"%,\t");
		stb.append("车辆上线率："+(vehicle_count <= 0 ? 0 : dft.format(obj.getVehicle_online_count()/vehicle_count))+"%,\t");
		
		int trackNum = obj.getTrack_normal()+obj.getException_track_count();
		stb.append("轨迹完整率："+dft.format(obj.getTrack_complete_rate())+"%,\t");
		stb.append("数据合格率："+(trackNum <= 0 ? 0 :dft.format(obj.getTrack_normal()/trackNum))+"%,\t");
		
		int sum = obj.getLocation_exception_count()+obj.getSpeed_160_count()+obj.getGpstime_exception_count()+obj.getHead_exception_count();
		int avg = sum<=0 ? 0 : obj.getLocation_exception_count() / sum;
		double result = obj.getVehicle_online_count() <= 0 ? 0 : (avg*obj.getException_vehicle_count())/obj.getVehicle_online_count();
		stb.append("定位漂移车辆比率："+dft.format(result*100)+"%,\t");
		stb.append("平均超速次数："+(obj.getVehicle_online_count() <= 0 ? 0 :dft.format(obj.getOverspeed_count()/obj.getVehicle_online_count()))+",\t");
		stb.append("平均疲劳驾驶时长："+(obj.getVehicle_online_count() <= 0 ? 0 :dft.format(obj.getTired_duration()/obj.getVehicle_online_count()))+",\t");
		stb.append("平台查岗响应率："+(obj.getCheck_count() <=0 ? 0 :dft.format(obj.getReply_correct_count()/obj.getCheck_count()))+"%,\t");
		return stb.toString();
	}

	
	
}
